﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using MvcEngine.Core.Localization;

namespace MvcEngine.Core.Validation
{
    /// <summary>
    /// Validates string value to match a provided regular expression.
    /// </summary>
    public class RegularExpressionValidatorAttribute : FieldValidatorAttribute
    {
        private string expression;

        public string Expression
        {
            get { return expression; }
            set { expression = value; }
        }

        private bool allowEmpty;

        /// <summary>
        /// Initializes a new instance of the <see cref="RegularExpressionValidatorAttribute"/> class.
        /// </summary>
        /// <param name="validationExpression">The validation expression.</param>
        /// <param name="allowEmptyField">If set to <see langword="true"/>, empty field is allowed.</param>
        public RegularExpressionValidatorAttribute(string message, string validationExpression, bool allowEmptyField)
            : base(message, true)
        {
            if (validationExpression.StartsWith("$"))
            {
                string res = ResourceReader.Current.GetString(validationExpression);
                if (string.IsNullOrEmpty(res))
                {
                    expression = validationExpression;
                }
                else
                {
                    expression = res;
                }
            }
            else 
            {
                expression = validationExpression;
            }
            allowEmpty = allowEmptyField;
            ErrorMessage = Message;
        }

        /// <summary>
        /// Determines whether the specified value is valid.
        /// </summary>
        /// <param name="value">The value to validate.</param>
        /// <returns>
        /// 	<see langword="true"/> if the specified value is valid; otherwise, <see langword="false"/>.
        /// </returns>
        public override bool IsValid(object value)
        {
            if (value == null && allowEmpty)
                return true;

            string val = value as string;
            if (val != null)
            {
                if (string.IsNullOrEmpty(val) && allowEmpty)
                    return true;
                Regex regularExpression = new Regex(expression);
                return regularExpression.IsMatch(val);
            }
            else
            {
                
                return false;
            }
        }
    }
}
